//
//  WBRefreshControl.swift
//  Weibo10
//
//  Created by 刘凡 on 15/10/21.
//  Copyright © 2015年 itheima. All rights reserved.
//

import UIKit

/// 下拉刷新动画偏移量
private let WBRefreshControlOffset: CGFloat = -60

/// 微博刷新控件 - 负责刷新业务逻辑
class WBRefreshControl: UIRefreshControl {
    
//    override func endRefreshing() {
//        super.endRefreshing()
//        
//        refreshView.stopAnimation()
//    }
//    
//    override func beginRefreshing() {
//        super.beginRefreshing()
//        
//        refreshView.startAnimation()
//    }
    // 重写开始刷新操作
    override func beginRefreshing() {
        super.beginRefreshing()
        // 自定义刷新（开始播放动画）
        refreshView.startAnimation()
    }
    // MARK: - 重写结束刷新操作
    override func endRefreshing() {
        super.endRefreshing()
        // 自定义结束刷新(结束播放动画)
        refreshView.stopAnimation()
    }
    
    // MARK: - 构造函数
    override init() {
        super.init()
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
    }
    
    // MARK: - KVO 监听方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 判断y值
        if frame.origin.y > 0 {
            return
        }
        if frame.origin.y < WBRefreshControlOffset && !refreshView.rotateFlag {
            refreshView.rotateFlag = !refreshView.rotateFlag
            // 刷新数据
            //HMHomeTableViewController().loadData()
            return
        }
        else if frame.origin.y > WBRefreshControlOffset && refreshView.rotateFlag {
            refreshView.rotateFlag = !refreshView.rotateFlag
        }
    }

    // MARK: - 设置界面
    /// 设置界面
    private func setupUI() {
        // 0. 清空转轮颜色
        tintColor = UIColor.clearColor()
        
        // 1. 添加控件
        addSubview(refreshView)
        
        // 2. 自动布局
        refreshView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX)
            make.centerY.equalTo(self.snp_centerY)
            make.size.equalTo(refreshView.bounds.size)
        }
        
        // 3. KVO 监听
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.addObserver(self, forKeyPath: "frame", options: [], context: nil)
        }
    }
    
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    // MARK: - 懒加载控件
    private lazy var refreshView: WBRefreshView = WBRefreshView.refreshView()
}

/// 微博刷新视图 - 负责刷新动画显示
class WBRefreshView: UIView {
    
    /// 旋转标记
    private var rotateFlag = false {
        didSet {
           rotateTipIcon()
        }
    }
    
    /// 提示视图
    @IBOutlet weak var tipView: UIView!
    /// 旋转提示图标
    @IBOutlet weak var tipIconView: UIImageView!
    /// 加载图标
    @IBOutlet weak var loadingIcon: UIImageView!
    
    /// 加载 XIB
    class func refreshView() -> WBRefreshView {
        
        let nib = UINib(nibName: "WBRefreshView", bundle: nil)
        
        return nib.instantiateWithOwner(nil, options: nil).last as! WBRefreshView
    }

    /// MARK -旋转提示图标
    private func rotateTipIcon() {
        var angle = CGFloat(M_PI)
        // 判断旋转标示符
        angle += rotateFlag ? 0.00000001 : -0.00000001
        if rotateFlag {
            WBRefreshControl().beginRefreshing()
        }
        // 动画旋转图标
        UIView.animateWithDuration(0.5) { () -> Void in
            self.tipIconView.transform = CGAffineTransformRotate(self.tipIconView.transform, angle)
        }
    }
//    
    private func startAnimation() {
        // 动画开始前需要把顶部视图隐藏
        tipView.hidden = true
        // 设置路径键值
        let keyPath = "transform.rotation"
        // 判断动画是否正在进行
        if let _ = loadingIcon.layer.animationForKey(keyPath) {
            return
        }
        // 创建动画
        let anim = CABasicAnimation(keyPath: keyPath)
        // 设置动画属性
        anim.toValue = 2 * M_PI
        anim.duration = 2
        anim.repeatCount = MAXFLOAT
        // 当完成动画时，不移除动画
        anim.removedOnCompletion = false
        // 把动画添加到控件上
        loadingIcon.layer.addAnimation(anim, forKey: keyPath)
    }
    /// 停止动画
    private func stopAnimation() {
        tipView.hidden = false
        
        loadingIcon.layer.removeAllAnimations()
    }

}
